package com.example.readerapp.myandserver.mybookconfig;

import android.content.Context;
import android.os.Environment;
import android.widget.Toast;
import com.example.readerapp.myandserver.util.FindWordFromDir;
import com.example.readerapp.myandserver.util.FormatBookUtil;
import com.example.readerapp.myandserver.util.FormatSaveUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import static com.example.readerapp.myandserver.util.FindWordFromDir.ImitateFindWordFromFile;

public class MyBookConfig
{
   public static String root= "/storage/emulated/0/";//Environment.getExternalStorageDirectory().getAbsolutePath()
    public static  String parentDir=root+"A_HUANG_WEI_MIN/";
    public static  String basePath=parentDir+"book/";//存储转换好的书籍
    //存储书籍阅读进度,文件版本
   // public static  String readProgress=parentDir+"阅读进度.txt";//不再使用
    public static  String tempPdfPath=parentDir+"pdf/";//用于临时存储用户上传的pdf文件
    public static  String tempFilePath=parentDir+"temp/";
    public static  String localTranslateDir=parentDir+"新牛津英汉双解词典.txt";

    public static String tempTTSPath=parentDir+"tts.mp3";//文字转语音得到的零时文件保存路径

    //存储书籍阅读进度相关信息,数据库版本
    public static String myDatabasePath=parentDir+"bookInfo.db";
    //初始化项目所需的依赖目录，复制assets中的书籍数据
    public static void initDir(Context context,String rootPath)
    {
        boolean success=true;
        root=rootPath+"/";
        // String root= "/storage/emulated/0";
        //String parentDir=root+"/A_HUANG_WEI_MIN/";
        //String basePath=parentDir+"book/";//存储转换好的书籍
        //存储书籍阅读进度
        File p=new File(parentDir);
        if(!p.exists())
        {
            if(!p.mkdir()){
               // Toast.makeText(context,"创建"+p.getAbsolutePath()+" 异常",Toast.LENGTH_LONG).show();
                System.out.println("创建"+p.getAbsolutePath()+"异常");
                success=false;
            };
        }

        File f=new File(basePath);
        if(!f.exists())
        {
            if (!f.mkdir())
            {
               // Toast.makeText(context,"创建"+f.getAbsolutePath()+" 异常",Toast.LENGTH_LONG).show();
                success=false;
            }
            ;
        }
        if(success)
        {
            //初始化数据库
            MyDatabase.initMyDatabase();
            /*初始化书籍阅读进度*/
            BookInfoTable bookInfoTable = new BookInfoTable();
            if (!bookInfoTable.exists())
            {
                try
                {
                    bookInfoTable.creatBookInfoTable();
                    File[] b = f.listFiles();
                    for (int i = 0; i < b.length; i++)
                    {
                        //FormatSaveUtil.save(readProgress, new String[]{b[i].getName(),"当前页:1"});
                        bookInfoTable.insertBookInfo(b[i].getName(), 1);
                    }

                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }

            try
            {
                //获取src/main/assets/book/目录下的所有文件的文件名称:supreme-magus_未完结.zip带后缀
                String[] list = context.getAssets().list("book/");
                for (String s : list)
                {
                    copyAssetsFile(context, "book/" + s, basePath + s);
                    //     System.out.println("尝试:"+s);
                }
                copyAssetsFile(context, "新牛津英汉双解词典.txt", parentDir + "新牛津英汉双解词典.txt");

            }
            catch (Exception e)
            {
                System.out.println("尝试失败" + e.getMessage());
                e.printStackTrace();
            }
        }else
        {
            Toast.makeText(context,"创建文件失败",Toast.LENGTH_LONG).show();
        }
    }
    /**
     * 将//获取src/main/assets/目录下的文件的文件复制到手机指定的文件夹中
     * @param context context
     * @param assetFileName 参考值：book/test.zip （src/main/assets/book/test.zip）
     * @param phonePath 参考值：/storage/emulated/0/HUANGWEIMIN/BOOK/test.zip
     *
     * */
    public static void copyAssetsFile(Context context, String assetFileName, String phonePath) {
        try {
            File f=new File(phonePath);
            if(!f.exists())
            {
                InputStream inputStream=context.getAssets().open(assetFileName);
                //  System.out.println("尝试:"+inputStream.available());
                FileOutputStream fileOutputStream=new FileOutputStream(phonePath);
                //这里开始拷贝
                int len = -1;
                byte[] buffer = new byte[1024];
                while ((len = inputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, len);
                }
                fileOutputStream.close();//用完了，记得关闭
                inputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void initDir(BookInfoTable bookInfoTable)
    {
        MyDatabase.initMyDatabase();
        File p=new File(parentDir);
        if(!p.exists())
        {
            if(!p.mkdir()){
                System.out.println("创建"+p.getAbsolutePath()+"异常");
            };
        }

        File f=new File(basePath);
        if(!f.exists())
            if(!f.mkdir()){
                System.out.println("创建"+f.getAbsolutePath()+"异常");

            };

        if(!bookInfoTable.exists())
        {
            try
            {
               bookInfoTable.creatBookInfoTable();
                File[] b=f.listFiles();
                for(int i=0;i<b.length;i++)
                {
                    //FormatSaveUtil.save(readProgress,new String[]{b[i].getName(),"当前页:1"});
                    bookInfoTable.insertBookInfo(b[i].getName(),1);
                }

            }catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        //FormatBookUtil.consistency(readProgress, basePath);
        FormatBookUtil.consistency(bookInfoTable,basePath);
     /*   File tempPdfDir=new File(tempPdfPath);
        if(!tempPdfDir.exists())
            if(!tempPdfDir.mkdir()){
                System.out.println("创建"+tempPdfDir.getAbsolutePath()+"异常");
            };*/
    }
    /*从词典查词*/
    public static String getWordFromDic(String findFromDir, String text)
    {
        try
        {
            text=text.replaceAll("\\.","");
            text=text.replaceAll(",","");
            FormatSaveUtil.separatorOfElem="--E--";
            FormatSaveUtil.separatorOfUnite="----U----";
            FormatSaveUtil.save(parentDir+"查词历史.txt",new String[]{text});
            FindWordFromDir.FindWordResult resultD = ImitateFindWordFromFile(FindWordFromDir.新牛津英汉双解词典, localTranslateDir, text, FindWordFromDir.levenshtein);
            if (resultD.directContain.size() > 0)
            {
                for(int i=0;i<resultD.directContain.size()/2;i++)
                {
                    findFromDir=findFromDir+"<p>"+(i+1)+"."+resultD.directContain.get(i)+"</p>";
                }
            }
            if (resultD.indirectContain.size() > 0)
            {
                findFromDir=findFromDir+"<p>间接包含</p>";
                for(int i=0;i<resultD.indirectContain.size();i++)
                {
                    findFromDir=findFromDir+"<p>"+(i+1)+resultD.indirectContain.get(i)+"</p>";
                }
            }
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        return findFromDir;
    }

}
